#!/bin/bash

function line_num(){
    if [ $# != 2 ]
	then
		echo $1
		echo "useage $0 serachStr file"
		echo ""
	else
		local retval=`grep -n $1 $2 |sed -n '1p'| awk -F ':' '{ print \$1 }'`
		echo $retval
	fi
}

function restart_port(){
	local line_num_of_request_port=`line_num $1 $3`
	local line_num_of_deploy_port=`line_num $2 $3`

	if [ $line_num_of_request_port -gt $line_num_of_deploy_port ]
		then
			echo $1
		else
			echo $2
	fi
}

# Return pid for port
# param1 required port
function pid_for_port {
	local restart_pid=$(lsof -i:$1 | sed -n "2p" | awk '{print $2}')
	echo $restart_pid
}

# tomcat path for pid
# param1 required pid
function tomcat_path_for_pid {
	local tomcat_path=`ps -ef | grep $1 | tr -s ' ' '\\n' | grep "Dcatalina.home" | tr -s '=' '\\n' | sed -n "2p"`
	echo $tomcat_path
}

# replace string in file
# param1 search string
# param2 replace string
# param3 file path
function replace_str_in_file {
	sed -i -e "s/$1/$2/g" $3
}

# need to change params begin
def_request_port=$1
def_deploy_port=$2
nginx_home="/usr/local/nginx"
nginx_conf="${nginx_home}/conf/conf.d/$3"
# need to change params end

echo "params: $1 $2 $3"

# step 1. Get restart tomcat's port
restart_port=$(restart_port $def_request_port $def_deploy_port $nginx_conf)
to_be_request_port=""
if [ $restart_port -eq $def_request_port ]
	then
		to_be_request_port=$def_deploy_port
	else
		to_be_request_port=$def_request_port
fi

# step 2. Get restart tomcat's pid
restart_pid=$(pid_for_port $restart_port)

# step 3. Get restart tomcat's home path
restart_path=$(tomcat_path_for_pid $restart_pid)

# step 4. restart and clean tomcat
kill -9 ${restart_pid}
echo "kill and restart tomcat port:${restart_port} pid:${restart_pid}, path:${restart_path}"
rm -rf $restart_path/logs/*
$restart_path/bin/startup.sh

# replace nginx port
echo "reload nginx, request port from ${restart_port} to ${to_be_request_port}"
replace_str_in_file $to_be_request_port "_TMP_PORT" $nginx_conf
replace_str_in_file $restart_port $to_be_request_port $nginx_conf
replace_str_in_file "_TMP_PORT" $restart_port $nginx_conf

sudo $nginx_home/sbin/nginx -s reload